from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
#文件上传的包
from django.core.files.storage import default_storage
import uuid
from testbanner import models,testser
from rest_framework.generics import ListAPIView
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination

class  Upload(APIView):
    def post(self,request):
        #1、获取要上传的文件对象
        file=request.data.get("file","")
        if not file:
            return Response({"msg":"请上传文件","code":400})
        #2、判断上传的类型是否合适
        allowtype=["image/jpeg","image/png","image/gif"]#设置允许的类型
        if file.content_type not in allowtype:
            return Response({"msg":"上传的文件类型不合适","code":400})
        #3、判断文件的大小是否合适 b->kb->mb 大小要求2mb
        if file.size>2*1024*1024:
            return Response({"msg":"上传的文件过大","code":400})
        #4、将文件保存到服务器上  23.jpg   新名.jpg
        #4.1、生成一个随机的文件名
        #获取后缀名
        suffix=file.name.split(".")[-1]
        filename=str(uuid.uuid4())+"."+suffix
        #4.2、保存文件 bann/ 是文件夹的名字 如果没有这个文件夹 会自动创建
        path=default_storage.save("bann/"+filename,file)
        #4.3、返回文件保存的路径
        return Response({"msg":"上传成功","code":200,"path":"uploads/"+path})

class AddBanner(APIView):
    def post(self,request):
        #标题需要唯一
        title=request.data.get("title","")
        sort=request.data.get("sort",0)
        imgurl=request.data.get("imgurl","")
        if not title or not imgurl:
            return Response({"msg":"标题和图片不能为空","code":400})
        #判断标题是否唯一
        info=models.TestBanner.objects.filter(title=title).first()
        if info:
            return Response({"msg":"标题已存在","code":400})
        #保存
        ser=testser.TestBannerSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"添加成功","code":200})
        return Response({"msg":"添加失败","code":400,"error":ser.errors})

from rest_framework.pagination import PageNumberPagination
class BannerPage(PageNumberPagination):
    page_size=2
    page_size_query_param="size"

class BannerList(ListAPIView):
    queryset=models.TestBanner.objects.filter(isdel=False).order_by("sort")
    serializer_class=testser.TestBannerSerializer
    pagination_class = BannerPage

class TopBanner(APIView):
    def put(self,request):
        #获取id
        id=request.data.get("id","")
        if not id:
            return Response({"msg":"id不能为空","code":400})
        #获取当前对象
        info=models.TestBanner.objects.filter(id=id).first()
        #获取到当前对象的上一条对象
        info1=models.TestBanner.objects.filter(sort__lt=info.sort,isdel=False).order_by("sort").first()
        newsort=info.sort
        info.sort=info1.sort
        info1.sort=newsort
        info.save()
        info1.save()
        return Response({"msg":"修改成功","code":200})

#导入缓存
from django.core.cache import cache
class Buy(APIView):
    def post(self,request):
        user=request.data.get("user","")#用户id
        book=request.data.get("book","")#图书id
        #根据图书id拿到图书信息
        bookinfo=models.Book.objects.filter(id=book).first()
        #先拿混存的数据
        key="book_"+str(user)
        info=cache.get(key,[])#如果没有就返回空列表
        #判断是否已经借出过
        # if bookinfo.name in info:
        #     return Response({"msg":"已经借出过","code":400})
        #添加到缓存中
        info.insert(0,bookinfo.name)
        cache.set(key,info,60*60)
        bookinfo.isuse = False
        bookinfo.save()
        return Response({"msg":"添加成功","code":200})

class History(APIView):
    def get(self,request):
        user=request.query_params.get("user","")#用户id
        if not user:
            return Response({"msg":"用户id不能为空","code":400})
        #先拿混存的数据
        key="book_"+str(user)
        info=cache.get(key,[])#如果没有就返回空列表
        return Response({"data":info,"code":200})

class Book(ListAPIView):
    queryset = models.Book.objects.all().order_by("-id")
    serializer_class = testser.BookSerializer
    pagination_class = BannerPage

